import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { viteMockServe } from 'vite-plugin-mock'
import DefineOptions from 'unplugin-vue-define-options/vite'

const root = process.cwd()
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  let env: any = {}
  const isBuild = command === 'build'
  if (!isBuild) {
    env = loadEnv('dev', root)
  } else {
    env = loadEnv(mode, root)
  }
  return {
    base: env.VITE_BASE_PATH,
    plugins: [
      vue({
        script: {
          defineModel: true
        }
      }),
      DefineOptions(),
      vueJsx(),
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()]
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    build: {
      target: ['esnext']
    },
    server: {
      port: 3000,
      open: false, //自动打开
      base: './ ', //生产环境路径
      proxy: {
        // 本地开发环境通过代理实现跨域，生产环境使用 nginx 转发
        // 正则表达式写法
        '^/api': {
          target: 'http://47.95.209.182:8099', // 后端服务实际地址
          // 需要和目标服务器的端口号一致
          ws: true,
          // 如果需要代理跨域的websocket
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    }
  }
})
